﻿using System;
using System.Drawing;
using System.Windows.Forms;
using SFAR.RibbonControlLibrary;
using SFAR.XmlConfig;
using System.Globalization;
using System.Diagnostics;
using Microsoft.Win32;

namespace RibbonControler
{
    public partial class Form1 : Form
    {
        RibbonControl controller;

        Bitmap HSLbitmap;

        Bitmap preview;
        private int fps;


        private ColorPanels cp;
        private int screenWidth, screenHeight, screenX, screenY;

        #region settings
        private int regionsTop = 0, regionsLeft = 0, regionsRight = 0, regionsBottom = 0, regionPercent = 20;
        private int marginTop = 0, marginBottom = 0, marginLeft = 0, marginRight = 0;
        private int screenNo = 0;
        private string profileName = "Default";
        #endregion

        Bitmap screenshotBitmap;
        Graphics screenshotGraphics;

        XmlConfig xcfg;

        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        KeyboardHook hook = new KeyboardHook();

        public Form1(string[] args)
        {
            InitializeComponent();

            hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);
            hook.RegisterHotKey(RibbonControler.ModifierKeys.Control | RibbonControler.ModifierKeys.Alt, Keys.R);

            try
            {
                switch (CultureInfo.CurrentCulture.Name)
                {
                    case "pl-PL":
                        label17.Text = "Wersja oprogramowania: " + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
                        break;
                    default:
                        label17.Text = "Software Version: " + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
                        break;
                }
            }
            catch
            {
            }


            controller = new RibbonControl(1);
            controller.OnSpecifiedDeviceArrived += new EventHandler(controller_OnSpecifiedDeviceArrived);
            controller.OnSpecifiedDeviceRemoved += new EventHandler(controller_OnSpecifiedDeviceRemoved);
            controller.OnDeviceSettingsRead += new EventHandler(controller_OnDeviceSettingsRead);

            createHSLBitmap();

            for (int i = 0; i < Screen.AllScreens.Length; i++)
            {
                screensCmb.Items.Add((i + 1).ToString());
            }

            loadSettings();

            try
            {
                screensCmb.SelectedIndex = screenNo;
            }
            catch
            {
                screensCmb.SelectedIndex = 0;
            }

            createBitmap();

            

            if (rkApp.GetValue("RibbonControl") == null)
            {
                checkBox5.Checked = false;
            }
            else
            {
                checkBox5.Checked = true;
            }

            if (Application.UserAppDataRegistry.GetValue("MinimizeTray") != null)
            {
                checkBox6.Checked = Convert.ToBoolean(Application.UserAppDataRegistry.GetValue("MinimizeTray"));
            }

            if (Application.UserAppDataRegistry.GetValue("MaxFPS") != null)
            {
                maxFPSTB.Value = Convert.ToUInt16(Application.UserAppDataRegistry.GetValue("MaxFPS"));
            }

            if (Application.UserAppDataRegistry.GetValue("SmoothingRatio") != null)
            {
                smoothingRatio.Value = Convert.ToUInt16(Application.UserAppDataRegistry.GetValue("SmoothingRatio"));
            }

            if (Application.UserAppDataRegistry.GetValue("BrightnessChb") != null)
            {
                checkBox1.Checked = Convert.ToBoolean(Application.UserAppDataRegistry.GetValue("BrightnessChb"));
            }

            if (Application.UserAppDataRegistry.GetValue("Brightness") != null)
            {
                trackBar5.Value = Convert.ToUInt16(Application.UserAppDataRegistry.GetValue("Brightness"));
            }

            if (Application.UserAppDataRegistry.GetValue("SaturationChb") != null)
            {
                checkBox2.Checked = Convert.ToBoolean(Application.UserAppDataRegistry.GetValue("SaturationChb"));
            }

            if (Application.UserAppDataRegistry.GetValue("Saturation") != null)
            {
                trackBar4.Value = Convert.ToUInt16(Application.UserAppDataRegistry.GetValue("Saturation"));
            }

            if (Application.UserAppDataRegistry.GetValue("ABrightnessChb") != null)
            {
                checkBox3.Checked = Convert.ToBoolean(Application.UserAppDataRegistry.GetValue("ABrightnessChb"));
            }

            if (Application.UserAppDataRegistry.GetValue("ABrightness") != null)
            {
                trackBar2.Value = Convert.ToUInt16(Application.UserAppDataRegistry.GetValue("ABrightness"));
            }

            if (Application.UserAppDataRegistry.GetValue("ASaturationChb") != null)
            {
                checkBox4.Checked = Convert.ToBoolean(Application.UserAppDataRegistry.GetValue("ASaturationChb"));
            }

            if (Application.UserAppDataRegistry.GetValue("ASaturation") != null)
            {
                trackBar3.Value = Convert.ToUInt16(Application.UserAppDataRegistry.GetValue("ASaturation"));
            }

            //uruchomienie ze startem systemu
            if (Array.IndexOf(args, "-s") > -1)
            {
                button2_Click(null, null);
                this.WindowState = FormWindowState.Minimized;
            }
        }

        void hook_KeyPressed(object sender, KeyPressedEventArgs e)
        {
            if (timer1.Enabled)
                button3_Click(null, null);
            else
                button2_Click(null, null);
        }


        delegate void Del();

        void controller_OnDeviceSettingsRead(object sender, EventArgs e)
        {

            Del fV = delegate() { label16.Text = "Firmware Version: " + (controller.firmwareVersion / 10.0).ToString().Replace(',', '.'); };
            
            try
            {
                switch (CultureInfo.CurrentCulture.Name)
                {
                    case "pl-PL":
                        label16.Invoke(fV);
                        break;
                    default:
                        label16.Invoke(fV);
                        break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            Del bC = delegate() { panel1.BackColor = controller.startColor; };
            panel1.Invoke(bC);
            Del sL = delegate() { stripLenghtTb.Text = controller.length.ToString(); };
            stripLenghtTb.Invoke(sL);
        }

        void controller_OnSpecifiedDeviceRemoved(object sender, EventArgs e)
        {
            switch (CultureInfo.CurrentCulture.Name)
            {
                case "pl-PL":
                    connectedStatus.Text = "Rozłączony";
                    break;
                default:
                    connectedStatus.Text = "Disconnected";
                    break;
            }
        }

        void controller_OnSpecifiedDeviceArrived(object sender, EventArgs e)
        {
            switch (CultureInfo.CurrentCulture.Name)
            {
                case "pl-PL":
                    connectedStatus.Text = "Połączony";
                    break;
                default:
                    connectedStatus.Text = "Connected";
                    break;
            }


        }

        private void createBitmap()
        {
            if ((screenWidth - marginLeft - marginRight) > 0 && (screenHeight - marginTop - marginBottom) > 0)
            {
                if (screenshotBitmap != null)
                    screenshotBitmap.Dispose();
                if (screenshotGraphics != null)
                    screenshotGraphics.Dispose();

                screenshotBitmap = new Bitmap(screenWidth - marginLeft - marginRight, screenHeight - marginTop - marginBottom);
                screenshotGraphics = Graphics.FromImage(screenshotBitmap);
            }
            createPanels();
        }




        void createHSLBitmap()
        {
            int picBoxWidth = pictureBox1.Size.Width;
            int picBoxHeight = pictureBox1.Size.Height;
            int halfWidth = pictureBox1.Size.Width / 2;
            int halfHeight = pictureBox1.Size.Height / 2;

            
            HSLbitmap = new Bitmap(picBoxWidth, picBoxHeight);

            HSLColor color = new HSLColor();
            color.Saturation = 1.0;

            for (int i = 0; i < 480; i++)
            {
                for (int j = 0; j < 480; j++)
                {
                    color.Hue = j / 480.0;
                    color.Luminosity = i / 480.0;
                    HSLbitmap.SetPixel(i, j, (Color)color);
                }
            }

            pictureBox1.Image = HSLbitmap;
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            controller.RegisterHandle(Handle);
            base.OnHandleCreated(e);

        }

        protected override void WndProc(ref Message m)
        {
            if (controller != null)
                controller.ParseMessages(ref m);
            try
            {
                base.WndProc(ref m);	// pass message on to base form
            }
            catch
            {
            }

        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                int x = e.X;
                int y = e.Y;
                if (e.X < 0)
                    x = 0;
                if (e.Y < 0)
                    y = 0;
                if (e.X > pictureBox1.Width)
                    x = pictureBox1.Width;
                if (e.Y > pictureBox1.Height)
                    y = pictureBox1.Height;

                try
                {
                    Color c = HSLbitmap.GetPixel(x, y);

                    if (analogStripCb.Checked)
                        controller.RGB = c;

                    if (digitalStripCb.Checked)
                        for (int i = 0; i < controller.leds.Length; i++)
                            controller.leds[i] = c;
                }
                catch
                {
                }

            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            uint length = 1;
            uint.TryParse(stripLenghtTb.Text, out length);

            controller.stripLegth = length;

            if (effectsCmb.SelectedIndex == 0)
            {
                //tęcza
                for (int i = 0; i < controller.leds.Length; i++)
                {
                    HSLColor color = new HSLColor();
                    color.Saturation = 1;
                    color.Luminosity = 0.5;
                    color.Hue = i / (double)controller.leds.Length;
                    if (digitalStripCb.Checked)
                        controller.leds[i] = color;
                }
            }

            timer2.Enabled = true;
        }




        private void timer1_Tick(object sender, EventArgs e)
        {
            //count frames
            fps++;

            //make screenshot
            screenshotGraphics.CopyFromScreen(screenX + marginLeft, screenY + marginTop, 0, 0, new Size(screenshotBitmap.Width, screenshotBitmap.Height));


            int r, g, b, n;

            //calculate RGB for all regions
            for (int i = 0; i < cp.panels.Length; i++)
            {
                r = 0; g = 0; b = 0; n = 0;

                for (int x = cp.panels[i].x - marginLeft; x < cp.panels[i].x - marginLeft + cp.panels[i].w; x += 16)
                {
                    for (int y = cp.panels[i].y - marginTop; y < cp.panels[i].y - marginTop + cp.panels[i].h; y += 16)
                    {
                        Color c = screenshotBitmap.GetPixel(x, y);
                        r += c.R;
                        g += c.G;
                        b += c.B;
                        n++;
                    }
                }
                if (n == 0)
                    n = 1;
                cp.panels[i].panelColor = Color.FromArgb(r / n, g / n, b / n);

            }

            r = 0; g = 0; b = 0; n = 0;
            //oblicz kolory dla analoga
            for (int x = 0; x < screenshotBitmap.Width; x += screenshotBitmap.Width/20)
                for (int y = 0; y < screenshotBitmap.Height; y += screenshotBitmap.Height/20)
                {
                    Color c = screenshotBitmap.GetPixel(x, y);
                    r += c.R;
                    g += c.G;
                    b += c.B;
                    n++;
                }

            if (n == 0)
                n = 1;
            controller.RGB = Color.FromArgb(r / n, g / n, b / n);

            //pictureBox2.Invalidate();
            //pictureBox2.Update();
            //send data to ribbon
            SendToStrip();

        }

        void SendToStrip()
        {
            for (int i = 0; i < cp.panels.Length && i < controller.leds.Length; i++)
            {
                controller.leds[i] = cp.panels[i].panelColor;
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            controller.stripLegth = (uint)(regionsTop + regionsBottom + regionsLeft + regionsRight);
            timer1.Enabled = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            for (int i = 0; i < controller.leds.Length; i++)
            {
                controller.leds[i] = Color.Black;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            timer2.Enabled = false;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            switch (effectsCmb.SelectedIndex)
            {
                case 0:
                    scrollRibbon();
                    break;
                case 1:
                    Flash(Color.White);
                    break;
                case 2:
                    Flash(Color.Red);
                    break;
                case 3:
                    Flash(Color.Green);
                    break;
                case 4:
                    Flash(Color.Blue);
                    break;
                case 5:
                    Flash(Color.Yellow);
                    break;
                case 6:
                    RGBFlash();
                    break;
                case 7:
                    RGBFade();
                    break;
            }

        }

        private void RGBFade()
        {
            HSLColor color;
            if (digitalStripCb.Checked)
                color = controller.leds[0];
            else
                color = controller.RGB;

            color.Saturation = 1;
            color.Luminosity = 0.5;
            if (color.Hue >= 1.0)
                color.Hue = 0;
            else
                color.Hue += 1/360.0;

            if (digitalStripCb.Checked)
                for (int i = 0; i < controller.leds.Length; i++)
                {
                    controller.leds[i] = color;
                }

            if (analogStripCb.Checked)
                controller.RGB = color;

        }

        private void RGBFlash()
        {
            Color color;
            if (controller.leds[0] == Color.Red)
                color = Color.Green;
            else if (controller.leds[0] == Color.Green)
                color = Color.Blue;
            else
                color = Color.Red;

            if (digitalStripCb.Checked)
                for (int i = 0; i < controller.leds.Length; i++)
                {
                    controller.leds[i] = color;
                }

            if (analogStripCb.Checked)
                controller.RGB = color;

        }

        private void Flash(Color color)
        {
            if (controller.leds[0] == Color.Black)
            {
                if (digitalStripCb.Checked)
                    for (int i = 0; i < controller.leds.Length; i++)
                    {
                        controller.leds[i] = color;
                    }

                if (analogStripCb.Checked)
                    controller.RGB = color;
            }
            else
            {
                if (digitalStripCb.Checked)
                    for (int i = 0; i < controller.leds.Length; i++)
                    {
                        controller.leds[i] = Color.Black;
                    }

                if (analogStripCb.Checked)
                    controller.RGB = Color.Black;
            }

        }

        private void scrollRibbon()
        {
            Color tmp = controller.leds[0];
            if (digitalStripCb.Checked)
                for (int i = 0; i < controller.leds.Length - 1; i++)
                {
                    controller.leds[i] = controller.leds[i + 1];
                }
            controller.leds[controller.leds.Length - 1] = tmp;

            if (analogStripCb.Checked)
                controller.RGB = tmp;
        }

        private void screensCmb_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (preview != null)
                preview.Dispose();
            screenWidth = Screen.AllScreens[screensCmb.SelectedIndex].Bounds.Width;
            screenHeight = Screen.AllScreens[screensCmb.SelectedIndex].Bounds.Height;
            screenX = Screen.AllScreens[screensCmb.SelectedIndex].Bounds.X;
            screenY = Screen.AllScreens[screensCmb.SelectedIndex].Bounds.Y;
            preview = new Bitmap(screenWidth, screenHeight);
            Graphics g = Graphics.FromImage(preview);
            g.CopyFromScreen(screenX, screenY, 0, 0, new Size(screenWidth, screenHeight));

            pictureBox2.Width = 450;
            pictureBox2.Height = (int)(preview.Height / (preview.Width / 450.0));

            pictureBox2.Invalidate();
            pictureBox2.Update();
            screenNo = screensCmb.SelectedIndex;
        }

        #region marginesy

        private void marginTxt_TextChanged(object sender, EventArgs e)
        {
            int res;
            if (int.TryParse((sender as TextBox).Text, out res))
            {
                if ((sender as TextBox).Name == "topMarginTxt")
                    marginTop = res;
                if ((sender as TextBox).Name == "bottomMarginTxt")
                    marginBottom = res;
                if ((sender as TextBox).Name == "leftMarginTxt")
                    marginLeft = res;
                if ((sender as TextBox).Name == "rightMarginTxt")
                    marginRight = res;

                createBitmap();
                createPanels();

                pictureBox2.Invalidate();
                pictureBox2.Update();

            }
        }

        #endregion


        #region regions

        private void createPanels()
        {
            cp = new ColorPanels(
                screenWidth, screenHeight,
                marginTop, marginLeft, marginRight, marginBottom,
                regionsBottom, regionsLeft, regionsTop, regionsRight,
                regionPercent
                );
        }

        private void regionsTxt_TextChanged(object sender, EventArgs e)
        {
            int res;
            if (int.TryParse((sender as TextBox).Text, out res))
            {
                if ((sender as TextBox).Name == "topRegionsTxt")
                    regionsTop = res;
                if ((sender as TextBox).Name == "bottomRegionsTxt")
                    regionsBottom = res;
                if ((sender as TextBox).Name == "leftRegionsTxt")
                    regionsLeft = res;
                if ((sender as TextBox).Name == "rightRegionsTxt")
                    regionsRight = res;
                createBitmap();
                createPanels();
                pictureBox2.Invalidate();
                pictureBox2.Update();

            }

        }

        private void saveSettings()
        {
            foreach (ConfigSetting cs in xcfg.Settings.GetNamedChildren("profile"))
            {
                if (cs["name"].Value == profileName)
                {
                    cs["marginBottom"].intValue = marginBottom;
                    cs["marginTop"].intValue = marginTop;
                    cs["marginLeft"].intValue = marginLeft;
                    cs["marginRight"].intValue = marginRight;

                    cs["regionsRight"].intValue = regionsRight;
                    cs["regionsTop"].intValue = regionsTop;
                    cs["regionsLeft"].intValue = regionsLeft;
                    cs["regionsBottom"].intValue = regionsBottom;
                    cs["regionPercent"].intValue = regionPercent;

                    cs["screenNo"].intValue = screenNo;
                }
            }

            xcfg.Commit();
        }

        private void reloadSettings()
        {
            if (xcfg.Settings.GetNamedChildrenCount("profile") > 0)
            {

                foreach (ConfigSetting cs in xcfg.Settings.GetNamedChildren("profile"))
                {

                    if (cs["name"].Value == profileName)
                    {
                        marginBottom = cs["marginBottom"].intValue;
                        marginTop = cs["marginTop"].intValue;
                        marginLeft = cs["marginLeft"].intValue;
                        marginRight = cs["marginRight"].intValue;

                        regionsRight = cs["regionsRight"].intValue;
                        regionsTop = cs["regionsTop"].intValue;
                        regionsLeft = cs["regionsLeft"].intValue;
                        regionsBottom = cs["regionsBottom"].intValue;

                        regionPercent = cs["regionPercent"].intValue;
                        screenNo = cs["screenNo"].intValue;
                    }
                }

            }

            topMarginTxt.Text = marginTop.ToString();
            leftMarginTxt.Text = marginLeft.ToString();
            rightMarginTxt.Text = marginRight.ToString();
            bottomMarginTxt.Text = marginBottom.ToString();

            topRegionsTxt.Text = regionsTop.ToString();
            leftRegionsTxt.Text = regionsLeft.ToString();
            rightRegionsTxt.Text = regionsRight.ToString();
            bottomRegionsTxt.Text = regionsBottom.ToString();

            percentTB.Value = regionPercent;
            screensCmb.SelectedItem = screenNo;
        }

        private void loadSettings()
        {
            xcfg = new XmlConfig("config.xml", true);


            if (xcfg.Settings.GetNamedChildrenCount("profile") > 0)
            {
                profileName = xcfg.Settings["profileName"].Value;
                profileCmb.Items.Clear();
                foreach (ConfigSetting cs in xcfg.Settings.GetNamedChildren("profile"))
                {
                    profileCmb.Items.Add(cs["name"].Value);
                }

                profileCmb.SelectedItem = profileName;
            }
            else
            {
                profileCmb.Items.Add("Default");

                xcfg.Settings["profileName"].Value = "Default";

                ConfigSetting newprofile = xcfg.Settings["profile##"];

                newprofile["name"].Value = "Default";
                newprofile["marginBottom"].intValue = marginBottom;
                newprofile["marginTop"].intValue = marginTop;
                newprofile["marginLeft"].intValue = marginLeft;
                newprofile["marginRight"].intValue = marginRight;
                newprofile["regionsRight"].intValue = regionsRight;
                newprofile["regionsTop"].intValue = regionsTop;
                newprofile["regionsLeft"].intValue = regionsLeft;
                newprofile["regionsBottom"].intValue = regionsBottom;
                newprofile["regionPercent"].intValue = regionPercent;

                xcfg.Commit();

                profileCmb.SelectedItem = profileName;
            }

            createPanels();
        }

        #endregion

        private void timer3_Tick(object sender, EventArgs e)
        {
            FPSLbl.Text = "FPS: " + fps.ToString("0.00");
            fps = 0;
            pictureBox2.Invalidate();
            pictureBox2.Update();
        }

        private void percentTB_MouseUp(object sender, MouseEventArgs e)
        {
            regionPercent = percentTB.Value;
            createPanels();
            pictureBox2.Invalidate();
            pictureBox2.Update();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            var newProfileName = Microsoft.VisualBasic.Interaction.InputBox("Enter new profile name", "New profile name");

            profileName = newProfileName;
            ConfigSetting newprofile = xcfg.Settings["profile##"];
            newprofile["name"].Value = newProfileName;
            profileCmb.Items.Add(newProfileName);
            profileCmb.SelectedItem = newProfileName;


        }

        private void profileCmb_SelectedIndexChanged(object sender, EventArgs e)
        {
            profileName = (string)profileCmb.SelectedItem;
            xcfg.Settings["profileName"].Value = (string)profileCmb.SelectedItem;
            reloadSettings();
            createPanels();
        }

        private void saveProfileBtn_Click(object sender, EventArgs e)
        {
            saveSettings();
        }

        private void smoothingRatio_Scroll(object sender, EventArgs e)
        {
            controller.smoothingRatio = smoothingRatio.Value;
        }

        private void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            timer2.Interval = trackBar1.Value;
        }

        private void maxFPSTB_ValueChanged(object sender, EventArgs e)
        {
            maxFPS.Text = maxFPSTB.Value.ToString();
            timer1.Interval = 1000 / maxFPSTB.Value;

            //zapis ustawień w rejestrze
            Application.UserAppDataRegistry.SetValue("MaxFPS", maxFPS.Text);
        }

        private void upgradeFirmwareBtn_Click(object sender, EventArgs e)
        {
            controller.goToBootloader();
        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            Single scale = 1.0F * preview.Width / pictureBox2.Width;
            e.Graphics.DrawImage(preview, 0, 0, pictureBox2.Width, pictureBox2.Height);

            SolidBrush b = new SolidBrush(Color.FromArgb(100, 0, 0, 255));

            using (b)
            {
                //top
                e.Graphics.FillRectangle(b, 0, 0, preview.Width / scale, marginTop / scale);
                //bottom
                e.Graphics.FillRectangle(b, 0, (preview.Height - marginBottom) / scale, preview.Width / scale, marginBottom / scale);
                //left
                e.Graphics.FillRectangle(b, 0, 0, marginLeft / scale, preview.Height / scale);
                //right
                e.Graphics.FillRectangle(b, preview.Width / scale - marginRight / scale, 0, marginRight / scale, preview.Height / scale);
            }

            b = new SolidBrush(Color.FromArgb(100, 255, 0, 0));

            using (b)
            {
                for (int i = 0; i < cp.panels.Length; i++)
                {
                    e.Graphics.FillRectangle(new SolidBrush(cp.panels[i].panelColor), cp.panels[i].x / scale, cp.panels[i].y / scale, cp.panels[i].w / scale, cp.panels[i].h / scale);
                    e.Graphics.DrawRectangle(new Pen(Color.Black, 10 / scale), cp.panels[i].x / scale, cp.panels[i].y / scale, cp.panels[i].w / scale, cp.panels[i].h / scale);
                    e.Graphics.DrawString((i + 1).ToString(), new Font("Tahoma", 10), new SolidBrush(Color.Black),
                        cp.panels[i].x / scale + cp.panels[i].w / scale / 2 - 16,
                        cp.panels[i].y / scale + cp.panels[i].h / scale / 2 - 16);
                }
            }
        }

        private void panel1_Click(object sender, EventArgs e)
        {
            ColorPicker cp = new ColorPicker();
            if (cp.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                panel1.BackColor = cp.panel2.BackColor;
            }
        }

        private void saveSettingsBtn_Click(object sender, EventArgs e)
        {
            uint len = Convert.ToUInt32(stripLenghtTb.Text);
            controller.sendSettings(StripType.UCS1903, len, panel1.BackColor);
        }



        private void trackBar5_ValueChanged(object sender, EventArgs e)
        {
            controller.DigitalBrightness = (uint)trackBar5.Value;
            Application.UserAppDataRegistry.SetValue("Brightness", (uint)trackBar5.Value);
        }

        private void trackBar4_ValueChanged(object sender, EventArgs e)
        {
            controller.DigitalSaturation = (uint)trackBar4.Value;
            Application.UserAppDataRegistry.SetValue("Saturation", (uint)trackBar4.Value);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            controller.DigitalBrightnessEnable = checkBox1.Checked;
            Application.UserAppDataRegistry.SetValue("BrightnessChb", checkBox1.Checked);
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            controller.DigitalSaturationEnable = checkBox2.Checked;
            Application.UserAppDataRegistry.SetValue("SaturationChb", checkBox2.Checked);
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            controller.AnalogBrightnessEnable = checkBox3.Checked;
            Application.UserAppDataRegistry.SetValue("ABrightnessChb", checkBox3.Checked);
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            controller.AnalogSaturationEnable = checkBox4.Checked;
            Application.UserAppDataRegistry.SetValue("ASaturationChb", checkBox4.Checked);
        }

        private void trackBar2_ValueChanged(object sender, EventArgs e)
        {
            controller.AnalogBrightness = (uint)trackBar2.Value;
            Application.UserAppDataRegistry.SetValue("ABrightness", (uint)trackBar2.Value);
        }

        private void trackBar3_ValueChanged(object sender, EventArgs e)
        {
            controller.AnalogSaturation = (uint)trackBar3.Value;
            Application.UserAppDataRegistry.SetValue("ASaturation", (uint)trackBar3.Value);
        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox5.Checked)
            {
                rkApp.SetValue("RibbonControl", Application.ExecutablePath.ToString() + " -s");
            }
            else
            {
                rkApp.DeleteValue("RibbonControl", false);
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (checkBox6.Checked)
            {
                if (FormWindowState.Minimized == this.WindowState)
                {
                    notifyIcon1.Visible = true;
                    notifyIcon1.ShowBalloonTip(500);
                    this.Hide();
                }
                else if (FormWindowState.Normal == this.WindowState)
                {
                    notifyIcon1.Visible = false;
                }
            }
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void checkBox6_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (checkBox6.Checked)
                {
                    Application.UserAppDataRegistry.SetValue("MinimizeTray", true);
                }
                else
                {
                    Application.UserAppDataRegistry.SetValue("MinimizeTray", false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void smoothingRatio_ValueChanged(object sender, EventArgs e)
        {
            Application.UserAppDataRegistry.SetValue("SmoothingRatio", smoothingRatio.Value);
        }







    }

    public class ColorPanels
    {
        int panelsNo;

        public ColorPanel[] panels;

        public ColorPanels(int width, int height, int mt, int ml, int mr, int mb, int b, int l, int t, int r, int percent)
        {
            panelsNo = b + l + t + r;

            panels = new ColorPanel[panelsNo];

            //lewy bok
            if (l > 0)
            {
                int lpheight = (height - mt - mb) / l;
                int lpwidth = (width - ml - mr) * percent / 100;
                for (int i = 0; i < l; i++)
                {
                    int x = ml;
                    int y = height - mb - lpheight * (i + 1);
                    panels[i] = new ColorPanel(x, y, lpwidth, lpheight, Color.FromArgb(100, 255, 0, 0));
                }
            }

            //górny bok
            if (t > 0)
            {
                int tpheight = (height - mt - mb) * percent / 100;
                int tpwidth = (width - ml - mr) / t;
                for (int i = 0; i < t; i++)
                {
                    int x = ml + tpwidth * i;
                    int y = mt;
                    panels[i + l] = new ColorPanel(x, y, tpwidth, tpheight, Color.FromArgb(100, 0, 255, 0));
                }
            }

            //prawy bok
            if (r > 0)
            {
                int rpheight = (height - mt - mb) / r;
                int rpwidth = (width - ml - mr) * percent / 100;
                for (int i = 0; i < r; i++)
                {
                    int x = width - mr - rpwidth;
                    int y = mt + rpheight * i;
                    panels[i + l + t] = new ColorPanel(x, y, rpwidth, rpheight, Color.FromArgb(100, 255, 0, 0));
                }
            }

            //dolny bok
            if (b > 0)
            {
                int bpheight = (height - mt - mb) * percent / 100;
                int bpwidth = (width - ml - mr) / b;
                for (int i = 0; i < b; i++)
                {
                    int x = ml + bpwidth * (b - i - 1);
                    int y = height - mb - bpheight;
                    panels[i + l + t + r] = new ColorPanel(x, y, bpwidth, bpheight, Color.FromArgb(100, 0, 255, 0));
                }
            }
        }
    }

    public class ColorPanel
    {
        public Color panelColor;
        public int x, y, w, h;
        public ColorPanel(int x, int y, int w, int h, Color c)
        {
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
            panelColor = c;
        }
    }


}
